const { sys_model_field, sys_model, querySql, op } = require("../../middleware/baseModel");

const handleRow = (row) => {
  let { data_type, defaultValue } = row;
  if (data_type === "INTEGER") {
    row.defaultValue = row.defaultValue || 0;

    if (row.data_length < 1 || row.data_length > 11) {
      row.data_length = 11;
    }
  } else if (data_type === "DOUBLE") {
    row.defaultValue = row.defaultValue || 0;

    if (row.data_length < 1 || row.data_length > 12) {
      row.data_length = 12;
    }
  }
};

module.exports = {
  "GET /sys_model_field/all": async (ctx, next) => {
    let model_id = ctx.get("model_id");

    let dbColKeys = [];
    let modelRow = await sys_model.findOne({ where: { id: model_id } });
    if (modelRow) {
      let isExistTableName = await querySql(`select TABLE_NAME from information_schema.TABLES where TABLE_NAME ="${modelRow.key}"`);
      if (isExistTableName && isExistTableName.length > 0) {
        let colRows = await querySql(`show columns from  ${modelRow.key}`);
        dbColKeys = colRows.map((p) => p.Field);
      }
    }

    let model_fields = await sys_model_field.findAll({ where: { model_id }, order: [["sort", "asc"]] });
    model_fields = model_fields.map((p) => {
      let newRow = p.toJSON();
      if (dbColKeys.indexOf(newRow.key) > -1) {
        newRow.isDbExist = true;
      } else {
        newRow.isDbExist = false;
      }
      return newRow;
    });

    return ctx.success(model_fields);
  },
  "GET /sys_model_field/allByKey": async (ctx, next) => {
    let key = ctx.get("key");

    let modelRow = await sys_model.findOne({ where: { key } });
    if (modelRow) {
      let model_id = modelRow.id;
      const resList = await sys_model_field.findAll({ where: { model_id }, order: [["sort", "asc"]] });
      return ctx.success(resList);
    }

    return ctx.fail();
  },

  "POST /sys_model_field/add": async (ctx, next) => {
    let row = ctx.getBody();

    handleRow(row);

    const res = await sys_model_field.create(row);
    return ctx.success(res);
  },
  "POST /sys_model_field/edit": async (ctx, next) => {
    let row = ctx.getBody();
    let { id } = row;
    handleRow(row);
    const res = await sys_model_field.update(row, {
      where: {
        id: id,
      },
    });
    return ctx.success(res);
  },
  "POST /sys_model_field/del": async (ctx, next) => {
    let id = ctx.get("id");
    const res = await sys_model_field.destroy({
      where: {
        id: id,
      },
    });
    return ctx.success(res);
  },
};
